from django.shortcuts import render

from django.http import HttpResponse,Http404,JsonResponse

from .. models import Goods,Types

from . Typesviews import gettypes

from . Userviews import uploads
from django.contrib.auth.decorators import permission_required




#商品添加页面
@permission_required('myadmin.insert_goods',raise_exception=True)

def add(request):
    
    con = {'goodslists':gettypes()}

    return render(request,'admin/good/add.html',con)


#商品执行添加
@permission_required('myadmin.insert_goods',raise_exception=True)

def insert(request):

    data = request.POST.dict()

    del data['csrfmiddlewaretoken']
    #判断是否有文件上传

    myfile = request.FILES.get('pic',None)

    if myfile:
        data['pic'] = uploads(myfile)
    else:
        return HttpResponse('<script>alert("必须上传图片");history.back(-1);</script>')
    #创建外键，它的值要是一个对象
    data['tid'] = Types.objects.get(id=data['tid'])
    #执行添加
    res = Goods.objects.create(**data)
    
    if res:
        return HttpResponse('<script>alert("商品添加成功");location.href="/admin/goods/index/"</script>')
    else:
        return HttpResponse('<script>alert("商品添加失败");history.back(-1)"</script>')

#商品页面
@permission_required('myadmin.show_goods',raise_exception=True)

def index(request):
    

    #获取所有商品

    goodslist = Goods.objects.filter()


    goods = request.GET.get('type',None)

    if goods:

        keywords = request.GET.get('keywords',None)

        

        data = {goods+'__contains':keywords}
        goodslist = goodslist.filter(**data)

       
        
        


    pageindex = request.GET.get('p',1)
    # 导入分页类
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(goodslist, 2)

    # 获取当前页的 数据
    goodslist = p.page(pageindex)

    

    #分配数据
    con = {'goodslist':goodslist}

    return render(request,'admin/good/index.html',con)
#商品删除
@permission_required('myadmin.del_goods',raise_exception=True)

def delete(request):
    #判断是否是ajax请求
    if request.is_ajax():

        try:

            ob = Goods.objects.get(id=request.GET['id'])

            ob.isDelete = True

            ob.save()
            

            return JsonResponse({'code':1,'msg':'删除成功'})
        
        
        except:
            return JsonResponse({'code':0,'msg':'删除失败'})
    

    else:
        # 返回一个404的错误页面
        raise Http404("Poll does not exist")
#商品编辑
@permission_required('myadmin.edit_goods',raise_exception=True)

def edit(request,gid):
    
    from web.settings import BASE_DIR
    #获取数据

    ob = Goods.objects.get(id=gid)

    #分配数据

    con = {'gl':ob,'goodslists':gettypes()}

    #判断请求方式

    if request.method == 'GET':

        return render(request,'admin/good/edit.html',con)

    elif request.method == 'POST':

        #执行修改
        try:
            ob.title = request.POST['title']
            ob.price = request.POST['price']
            ob.store = request.POST['store']
            ob.info = request.POST['info']

            #判断是否更新了头像
            myfile = request.FILES.get('pic',None)
            if myfile:


                
                #删除原有头像
                os.remove(BASE_DIR+ob.pic)
                ob.pic = uploads(myfile)
            ob.save()


            return HttpResponse('<script>alert("商品修改成功");location.href="/admin/goods/index/"</script>')
        except:
            return HttpResponse('<script>alert("商品修改成功");location.href="/admin/goods/index/"</script>')
   


